# _*_ coding: utf-8 _*_
"""
@ 时间    ：2024/10/24 16:20
@ 作者    ：旺财
@ 文件    ：04-1 LightGBM-客户违约预测模型.py
@ 说明    ：   
"""
import logging
import pandas as pd
from sklearn.model_selection import train_test_split,GridSearchCV
from lightgbm import LGBMClassifier
from sklearn.metrics import roc_auc_score,roc_curve
import matplotlib.pyplot as plt


df = pd.read_excel('客户信息及违约表现.xlsx')
print(df.head())

x = df.drop(columns='是否违约')
y = df['是否违约']

x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=123)

mode = LGBMClassifier(verbose=-1)
param = {
    'num_leaves': [10, 15, 31],
    'n_estimators': [10, 20, 30],
    'learning_rate': [0.05, 0.1, 0.2],
}
grid_search = GridSearchCV(mode, param, scoring='roc_auc', cv=5)
grid_search.fit(x_train, y_train)
best_mode = grid_search.best_estimator_
print(f'最优参数: {grid_search.best_params_}')

a = pd.DataFrame()
a['预测值'] = list(best_mode.predict(x_test))
a['实际值'] = list(y_test)
print(a.head())

score = best_mode.score(x_test, y_test)
print(f'准确率: {round(score*100, 2)}%')

y_proba = best_mode.predict_proba(x_test)[:, 1]
auc = roc_auc_score(y_test, y_proba)
print(f'ACU: {round(auc*100, 2)}%')

b = pd.DataFrame()
b['特征名称'] = x.columns
b['特征重要性'] = best_mode.feature_importances_
print(b.sort_values(by='特征重要性', ascending=False))

plt.rcParams['font.sans-serif'] = ['SimHei']
fpr, tpr, _ = roc_curve(y_test, y_proba)
plt.plot(fpr, tpr)
plt.title('ROC曲线')
plt.xlabel('fpr-误报率')
plt.ylabel('tpr-命中率')
plt.show()